import axios from 'axios'
import { Loading, Message } from 'element-ui'
import router from './router'

let loading
function staartLoading () {
    loading = Loading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0,0,0,.7)'
    })
}

function closeLoading () {
    loading.close()
}

// 请求拦截
axios.interceptors.request.use(config => {
    //加载动画
    staartLoading()
    // 设置token
    if (localStorage.token) {
        config.headers.token = localStorage.token
    }

    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截
axios.interceptors.response.use(response => {
    closeLoading()
    return response
}, error => {
    closeLoading()
    
    // token过期
    const { status } = error.response
    if (status == 401) {
        Message.error("token已过期，请重新登录")
        localStorage.removeItem('token')
        router.push('/login')
    } else{
        Message.error(error.response.data)
    }
    return Promise.reject(error)
})



export default axios